<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>宾果消消乐</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <!-- 卡通字体 -->
    <link href="https://fonts.googleapis.com/css2?family=Permanent+Marker&family=Fredoka+One&family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#FF5E87',
                        secondary: '#FFA6B9',
                        accent: '#FFD1DC',
                        dark: '#333333',
                        light: '#F9F9F9',
                        success: '#4CAF50',
                        warning: '#FFC107',
                        danger: '#FF5252',
                        info: '#2196F3',
                    },
                    fontFamily: {
                        comic: ['"Fredoka One"', '"Permanent Marker"', 'cursive'],
                        sans: ['"Noto Sans SC"', 'sans-serif'],
                    },
                }
            }
        };
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
            }
            .text-shadow-lg {
                text-shadow: 3px 3px 0px rgba(0, 0, 0, 0.1);
            }
            .bg-gradient-pink {
                background: linear-gradient(135deg, #FFC0CB 0%, #FF69B4 100%);
            }
            .bg-gradient-sweet {
                background: linear-gradient(135deg, #FFD1DC 0%, #FFB6C1 50%, #FF69B4 100%);
            }
            .bg-gradient-btn {
                background: linear-gradient(135deg, #FF5E87 0%, #FF2E63 100%);
            }
            .fruit-item {
                transition: all 0.2s ease-out;
            }
            .fruit-item:hover {
                transform: scale(1.05);
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            }
            .grid-container {
                display: grid;
                grid-template-columns: repeat(6, 1fr); /* 配合 gridSize 调整列数 */
                gap: 8px;
            }
            .score-popup {
                animation: scorePopup 0.8s ease-out forwards;
            }
            @keyframes scorePopup {
                0% { opacity: 1; transform: translateY(0); }
                100% { opacity: 0; transform: translateY(-30px); }
            }
            .time-progress {
                transition: width 1s linear;
            }
            .btn-hover {
                transition: all 0.3s ease;
            }
            .btn-hover:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            }
            .btn-pulse {
                animation: btnPulse 2s infinite;
            }
            @keyframes btnPulse {
                0% { box-shadow: 0 0 0 0 rgba(255, 94, 135, 0.7); }
                70% { box-shadow: 0 0 0 10px rgba(255, 94, 135, 0); }
                100% { box-shadow: 0 0 0 0 rgba(255, 94, 135, 0); }
            }
            .modal-transition {
                transition: opacity 0.3s ease, transform 0.3s ease;
            }
            .shake {
                animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
            }
            @keyframes shake {
                10%, 90% { transform: translate3d(-1px, 0, 0); }
                20%, 80% { transform: translate3d(2px, 0, 0); }
                30%, 50%, 70% { transform: translate3d(-4px, 0, 0); }
                40%, 60% { transform: translate3d(4px, 0, 0); }
            }
            .smooth-drop {
                transition: transform 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
            }
            .star-pulse {
                animation: starPulse 3s infinite alternate;
            }
            @keyframes starPulse {
                0% { transform: scale(1) rotate(0deg); opacity: 0.8; }
                100% { transform: scale(1.1) rotate(10deg); opacity: 1; }
            }
            .float {
                animation: float 3s ease-in-out infinite;
            }
            @keyframes float {
                0% { transform: translateY(0px); }
                50% { transform: translateY(-10px); }
                100% { transform: translateY(0px); }
            }
            .fruit-decoration {
                position: absolute;
                opacity: 0.2;
                z-index: 0;
            }
            .finger-point {
                animation: fingerPoint 2s infinite;
            }
            @keyframes fingerPoint {
                0% { transform: translateY(0) rotate(0deg); }
                50% { transform: translateY(-10px) rotate(5deg); }
                100% { transform: translateY(0) rotate(0deg); }
            }
            .rule-item {
                transition: all 0.3s ease;
            }
            .rule-item:hover {
                transform: scale(1.02);
            }
            .score-badge {
                animation: scoreBadge 0.5s ease-out;
            }
            @keyframes scoreBadge {
                0% { transform: scale(0); }
                70% { transform: scale(1.1); }
                100% { transform: scale(1); }
            }
            .share-btn {
                transition: all 0.3s ease;
            }
            .share-btn:hover {
                transform: scale(1.05);
            }
            .fruit-bounce-1 {
                animation: fruitBounce1 1s ease-in-out infinite;
            }
            @keyframes fruitBounce1 {
                0%, 100% { transform: translateY(0); }
                50% { transform: translateY(-15px); }
            }
            .fruit-bounce-2 {
                animation: fruitBounce2 1.2s ease-in-out infinite;
            }
            @keyframes fruitBounce2 {
                0%, 100% { transform: translateY(0); }
                50% { transform: translateY(-12px); }
            }
            .fruit-bounce-3 {
                animation: fruitBounce3 1.4s ease-in-out infinite;
            }
            @keyframes fruitBounce3 {
                0%, 100% { transform: translateY(0); }
                50% { transform: translateY(-18px); }
            }
            .fruit-bounce-4 {
                animation: fruitBounce4 1.1s ease-in-out infinite;
            }
            @keyframes fruitBounce4 {
                0%, 100% { transform: translateY(0); }
                50% { transform: translateY(-14px); }
            }
            .fruit-bounce-5 {
                animation: fruitBounce5 1.3s ease-in-out infinite;
            }
            @keyframes fruitBounce5 {
                0%, 100% { transform: translateY(0); }
                50% { transform: translateY(-16px); }
            }
            /* 修复Safari的动画渲染问题 */
            @keyframes vanish {
                0% { transform: scale(1); opacity: 1; }
                50% { transform: scale(1.2); opacity: 0.7; }
                100% { transform: scale(0); opacity: 0; }
            }

            .fruit-item {
                will-change: transform, opacity; /* 提升动画性能 */
            }

            .disappear {
                animation: vanish 0.5s ease-out forwards;
                @media (prefers-reduced-motion) {
                    transition: opacity 0.3s;
                    opacity: 0;
                }
            }
            .bomb-explode {
                animation: bombExplode 0.8s ease-out forwards;
            }
            @keyframes bombExplode {
                0% { transform: scale(1); opacity: 1; }
                50% { transform: scale(1.5); opacity: 0.7; }
                100% { transform: scale(2); opacity: 0; }
            }
        }
    </style>
</head>
<body class="bg-gradient-sweet min-h-screen font-sans text-dark p-4 flex items-center justify-center relative overflow-auto">
    <!-- 背景装饰元素 -->
    <div class="fruit-decoration text-6xl top-10 left-10 float" style="animation-delay: 0s;">🍎</div>
    <div class="fruit-decoration text-5xl top-20 right-16 float" style="animation-delay: 0.5s;">🍊</div>
    <div class="fruit-decoration text-7xl bottom-12 left-16 float" style="animation-delay: 1s;">🍓</div>
    <div class="fruit-decoration text-5xl bottom-20 right-10 float" style="animation-delay: 1.5s;">🍌</div>
    <div class="fruit-decoration text-6xl top-40 left-1/4 float" style="animation-delay: 2s;">🍉</div>
    <div class="fruit-decoration text-5xl bottom-40 right-1/4 float" style="animation-delay: 2.5s;">🍇</div>
    
    <!-- 游戏容器 -->
    <div class="max-w-4xl w-full bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl overflow-hidden relative z-10">
        <!-- 游戏头部 -->
        <header class="px-6 py-4 border-b border-gray-200 text-center relative">
            <div class="flex items-center justify-center">
                <!-- 左侧水果装饰 -->
                <div class="mr-3 text-4xl md:text-5xl star-pulse">🍓</div>
                
                <!-- 主标题 -->
                <h1 class="text-[clamp(2.2rem,5vw,3.2rem)] font-comic font-bold text-primary text-shadow-lg mb-2 relative">
                    宾果消消乐
                    <!-- 标题装饰元素 -->
                    <span class="absolute -top-4 -left-6 text-3xl star-pulse">🍎</span>
                    <span class="absolute -top-2 -right-8 text-3xl star-pulse">🍊</span>
                </h1>
                
                <!-- 右侧水果装饰 -->
                <div class="ml-3 text-4xl md:text-5xl star-pulse">🍇</div>
            </div>
            
            <!-- 游戏数据统计 -->
            <div class="mt-4 bg-accent/30 rounded-lg p-3 flex flex-wrap justify-center gap-4 items-center">
                <div class="flex items-center gap-2 bg-white/80 rounded-full px-4 py-2 shadow-sm">
                    <i class="fa-solid fa-gamepad text-primary"></i>
                    <span class="font-bold text-dark" id="playCount">今日挑战: 0次</span>
                </div>
                <div class="flex items-center gap-2 bg-white/80 rounded-full px-4 py-2 shadow-sm">
                    <i class="fa-solid fa-trophy text-primary"></i>
                    <span class="font-bold text-dark" id="highScore">最高分: 0</span>
                </div>
            </div>
        </header>

        <!-- 游戏主体 -->
        <main class="p-6">
            <!-- 游戏提示 -->
            <div class="mb-6 bg-primary/10 rounded-lg p-4">
                <div class="flex items-center gap-3 justify-center">
                    <i class="fa-regular fa-lightbulb text-primary text-xl"></i>
                    <div class="w-full">
                        <h3 class="font-comic font-bold text-dark text-lg text-center">游戏玩法</h3>
                        <div class="mt-2 grid grid-cols-3 gap-2 justify-items-center">
                            <div class="bg-white rounded-lg p-2 text-center rule-item w-full">
                                <div class="text-3xl mb-1">🍎🍎🍎</div>
                                <p class="text-xs">匹配三个相同水果</p>
                            </div>
                            <div class="bg-white rounded-lg p-2 text-center rule-item w-full">
                                <div class="text-3xl mb-1">🍐🍐🍐🍐</div>
                                <p class="text-xs">四连生成炸弹</p>
                            </div>
                            <div class="bg-white rounded-lg p-2 text-center rule-item w-full">
                                <div class="text-3xl mb-1">🍓🍓🍓🍓🍓</div>
                                <p class="text-xs">五连生成彩虹水果</p>
                            </div>
                        </div>
                        
                        <!-- 折叠面板 -->
                        <div id="rulePanel" class="mt-3 bg-white rounded-lg p-3 hidden">
                            <h4 class="font-semibold text-primary mb-2">高级玩法</h4>
                            <ul class="text-sm space-y-1">
                                <li class="flex items-start gap-2">
                                    <i class="fa-solid fa-bomb text-red-500 mt-1"></i>
                                    <span>炸弹: 消除周围3x3区域的所有水果</span>
                                </li>
                                <li class="flex items-start gap-2">
                                    <i class="fa-solid fa-star text-yellow-400 mt-1"></i>
                                    <span>彩虹水果: 消除所有同类型水果</span>
                                </li>
                                <li class="flex items-start gap-2">
                                    <i class="fa-solid fa-bolt text-blue-500 mt-1"></i>
                                    <span>闪电: 消除整行或整列的水果</span>
                                </li>
                            </ul>
                        </div>
                        
                        <button id="ruleToggle" class="mt-2 text-primary text-sm flex items-center gap-1 mx-auto justify-center">
                            <span>查看更多玩法</span>
                            <i class="fa-solid fa-chevron-down"></i>
                        </button>
                    </div>
                </div>
            </div>

            <!-- 游戏控制区 -->
            <div class="flex flex-col items-center justify-center mb-8">
                <!-- 动态水果动画 -->
                <div class="flex gap-2 mt-2 justify-center">
                    <div class="text-4xl fruit-bounce-1">🍎</div>
                    <div class="text-4xl fruit-bounce-2">🍊</div>
                    <div class="text-4xl fruit-bounce-3">🍓</div>
                    <div class="text-4xl fruit-bounce-4">🍇</div>
                    <div class="text-4xl fruit-bounce-5">🍉</div>
                </div>
                <!-- 新增按钮容器 -->
                <div class="flex gap-4 mt-4 justify-center">
                    <button id="startBtn" class="bg-gradient-btn hover:opacity-95 text-white px-8 py-3 rounded-lg shadow-lg btn-hover text-lg font-comic">
                        <i class="fa-solid fa-play text-2xl"></i>
                        <span>开始游戏</span>
                    </button>
                    <button id="playAgainBtn" class="bg-gradient-btn hover:opacity-95 text-white px-8 py-3 rounded-lg shadow-lg btn-hover text-lg font-comic hidden">
                        <i class="fa-solid fa-redo text-2xl"></i>
                        <span>再玩一次</span>
                    </button>
                    <button id="resetGameBtn" class="bg-gradient-btn hover:opacity-95 text-white px-8 py-3 rounded-lg shadow-lg btn-hover text-lg font-comic hidden">
                        <i class="fa-solid fa-rotate-left text-2xl"></i>
                        <span>重置游戏</span>
                    </button>
                </div>
                <!-- 激励语 -->
                <p class="text-gray-600 mt-4 text-center">匹配水果，冲击高分！</p>
            </div>

            <!-- 游戏区域 -->
            <div id="gameArea" class="hidden">
                <!-- 顶部信息栏，新增暂停按钮 -->
                <div class="flex justify-between items-center mb-4">
                    <div class="flex items-center gap-3">
                        <div class="flex items-center gap-1">
                            <i class="fa-regular fa-star"></i>
                            <span id="gameScore" class="font-bold">0</span>
                        </div>
                        <div class="flex items-center gap-1">
                            <i class="fa-regular fa-clock"></i>
                            <span id="gameTimer" class="font-bold">3:30</span>
                        </div>
                    </div>
                    <div class="flex items-center gap-8">
                        <div class="flex items-center gap-3">
                            <i class="fa-regular fa-flag text-2xl"></i>
                            <span id="gameTarget" class="font-bold text-lg">1000</span>
                        </div>
                        <button id="gameHintBtn" class="bg-secondary hover:bg-secondary/90 text-white px-4 py-2 rounded-lg shadow btn-hover flex items-center gap-2 text-base" disabled>
                            <i class="fa-regular fa-lightbulb text-xl"></i>
                            <span id="gameHintCount">9 次提示</span>
                        </button>
                        <button id="pauseBtn" class="bg-gradient-btn hover:opacity-95 text-white px-8 py-3 rounded-lg shadow-lg btn-hover text-lg font-comic">
                            <i class="fa-solid fa-pause text-2xl"></i>
                            <span>暂停游戏</span>
                        </button>
                    </div>
                </div>
                
                <!-- 网格容器 -->
                <div id="gameGrid" class="grid-container max-w-lg bg-white p-4 rounded-xl shadow-inner mx-auto"></div>
                
                <!-- 游戏开始遮罩 -->
                <div id="gameStartOverlay" class="absolute inset-0 bg-dark/60 flex flex-col items-center justify-center rounded-xl z-10 hidden"></div>
                
                <!-- 游戏结束遮罩 -->
                <div id="gameOverOverlay" class="absolute inset-0 bg-dark/60 flex items-center justify-center rounded-xl z-10 hidden">
                    <div id="gameResultModal" class="bg-white rounded-2xl p-8 max-w-md w-full text-center transform transition-all scale-95 opacity-0">
                        <h2 id="resultTitle" class="text-2xl font-comic font-bold text-primary mb-4">游戏结束!</h2>
                        <p id="resultMessage" class="text-gray-600 mb-2">恭喜你获得了 <span id="finalScore" class="font-bold text-dark">0</span> 分</p>
                        <div id="resultStars" class="flex justify-center gap-2 mb-6">
                            <i class="fa-regular fa-star text-gray-300 text-2xl"></i>
                            <i class="fa-regular fa-star text-gray-300 text-2xl"></i>
                            <i class="fa-regular fa-star text-gray-300 text-2xl"></i>
                        </div>
                        <!-- 新增重新开始游戏按钮 -->
                        <button id="restartAfterTimeUp" class="bg-gradient-btn hover:opacity-95 text-white px-8 py-3 rounded-lg shadow-lg btn-hover text-lg font-comic" onclick="resetGame()">
                            <i class="fa-solid fa-rotate-left text-2xl"></i>
                            <span>重新开始游戏</span>
                        </button>
                    </div>
                </div>
                
                <!-- 进度条 -->
                <div class="mt-6 h-2 bg-gray-200 rounded-full overflow-hidden">
                    <div id="timeProgress" class="time-progress h-full bg-primary" style="width: 100%;"></div>
                </div>
            </div>
        </main>

        <!-- 游戏底部 -->
        <footer class="px-6 py-3 bg-gray-50 flex flex-col md:flex-row justify-between items-center">
            <div class="text-sm text-gray-500 mb-2 md:mb-0">
                © 2025 宾果消消乐
            </div>
            <div class="text-primary font-comic">
                消除快乐，根本停不下来！
            </div>
            <div class="flex gap-3 mt-3 md:mt-0">
                <button id="privacyBtn" class="text-gray-500 hover:text-gray-700 text-sm">
                    隐私政策
                </button>
                <button id="termsBtn" class="text-gray-500 hover:text-gray-700 text-sm">
                    用户协议
                </button>
            </div>
        </footer>
    </div>

    <!-- 分享模态框 -->
    <div id="shareModal" class="fixed inset-0 bg-dark/70 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-2xl p-6 max-w-md w-full transform transition-all scale-95 opacity-0" id="shareModalContent">
            <h3 class="text-xl font-comic font-bold text-primary mb-4">分享游戏成绩</h3>
            <div class="bg-accent/20 rounded-lg p-4 mb-4">
                <div class="text-center mb-4">
                    <h4 class="font-bold text-dark">我在宾果消消乐中获得了</h4>
                    <div class="text-4xl font-comic font-bold text-primary score-badge">888</div>
                    <h4 class="font-bold text-dark">分！</h4>
                </div>
                <div class="flex justify-center gap-4">
                    <button class="bg-blue-500 hover:bg-blue-600 text-white p-3 rounded-full share-btn">
                        <i class="fa-brands fa-weixin text-xl"></i>
                    </button>
                    <button class="bg-green-500 hover:bg-green-600 text-white p-3 rounded-full share-btn">
                        <i class="fa-brands fa-weibo text-xl"></i>
                    </button>
                    <button class="bg-red-500 hover:bg-red-600 text-white p-3 rounded-full share-btn">
                        <i class="fa-brands fa-qq text-xl"></i>
                    </button>
                    <button class="bg-gray-800 hover:bg-gray-900 text-white p-3 rounded-full share-btn">
                        <i class="fa-solid fa-link text-xl"></i>
                    </button>
                </div>
            </div>
            <button id="closeShareBtn" class="w-full bg-gray-200 hover:bg-gray-300 text-gray-700 py-2 rounded-lg transition-all">
                关闭
            </button>
        </div>
    </div>

    <!-- 提示信息模态框 -->
    <div id="hintInfoModal" class="fixed inset-0 bg-dark/70 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-2xl p-6 max-w-md w-full transform transition-all scale-95 opacity-0" id="hintInfoContent">
            <h3 class="text-xl font-comic font-bold text-primary mb-4">如何获得更多提示？</h3>
            <ul class="space-y-3 mb-6">
                <li class="flex items-start gap-3">
                    <div class="bg-primary/10 rounded-full p-2 mt-1">
                        <i class="fa-solid fa-play text-primary"></i>
                    </div>
                    <div>
                        <h4 class="font-bold text-dark">完成每日任务</h4>
                        <p class="text-sm text-gray-600">每天完成指定任务可获得提示奖励</p>
                    </div>
                </li>
                <li class="flex items-start gap-3">
                    <div class="bg-primary/10 rounded-full p-2 mt-1">
                        <i class="fa-solid fa-video text-primary"></i>
                    </div>
                    <div>
                        <h4 class="font-bold text-dark">观看激励广告</h4>
                        <p class="text-sm text-gray-600">观看广告可立即获得额外提示</p>
                    </div>
                </li>
                <li class="flex items-start gap-3">
                    <div class="bg-primary/10 rounded-full p-2 mt-1">
                        <i class="fa-solid fa-gift text-primary"></i>
                    </div>
                    <div>
                        <h4 class="font-bold text-dark">邀请好友</h4>
                        <p class="text-sm text-gray-600">成功邀请好友可获得提示奖励</p>
                    </div>
                </li>
            </ul>
            <button id="closeHintInfoBtn" class="w-full bg-gray-200 hover:bg-gray-300 text-gray-700 py-2 rounded-lg transition-all">
                知道了
            </button>
        </div>
    </div>

    <!-- 独立目标达成弹窗 -->
    <div id="target-modal" class="fixed inset-0 bg-dark/60 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-2xl p-8 max-w-md w-full text-center">
            <div class="text-4xl">🎉 游戏通关！</div>
            <div>最终得分：<span class="score">1000</span></div>
            <button onclick="location.reload()" class="bg-gradient-btn hover:opacity-95 text-white px-8 py-3 rounded-lg shadow-lg btn-hover text-lg font-comic mt-4">再玩一次</button>
        </div>
    </div>

    <!-- 里程碑弹窗 -->
    <div id="milestone-modal" class="fixed inset-0 bg-dark/60 flex items-center justify-center z-50 hidden" aria-hidden="true">
        <div class="bg-white rounded-2xl p-8 max-w-md w-full text-center" role="dialog" aria-labelledby="milestone-title">
            <div id="milestone-title" class="text-2xl font-comic font-bold text-primary mb-4">
                恭喜达到<span class="milestone-score">150</span>分里程碑!
            </div>
            <button 
                class="bg-gradient-btn hover:opacity-95 text-white px-8 py-3 rounded-lg shadow-lg btn-hover text-lg font-comic mt-4" 
                onclick="this.parentElement.parentElement.classList.add('hidden')"
                aria-label="继续游戏"
            >
                继续游戏
            </button>
        </div>
    </div>
<!-- ... 已有代码 ... -->
    <script>
        // ====== 关键配置修复 ======
        const CONFIG = {
            targetScore: 1000,          // 修改目标分数为1000
            milestoneScores: [450, 550, 650, 750, 850], // 新增里程碑分数
            // ...其他配置
        };

        // 游戏配置
        const config = {
            gridSize: 6, // 修改网格尺寸为 6x6
            // 减少水果种类
            itemTypes: ['🍎', '🍌', '🍇', '🍊', '🍓', '🍉'], 
            targetScore: CONFIG.targetScore,
            // 修改倒计时时间为 3 分 30 秒（210 秒）
            timeLimit: 210, 
            // 修改提示冷却时间为 8 秒
            hintCooldown: 8, 
            hintCount: 9,
            milestoneScores: CONFIG.milestoneScores // 更新里程碑分数
        };

        // 游戏状态
        let gameState = {
            grid: [],
            score: 0,
            timeRemaining: config.timeLimit,
            isPlaying: false,
            firstSelected: null,
            timerInterval: null,
            hintAvailable: false,
            soundEnabled: true,
            hintCount: config.hintCount,
            playCount: 0,
            highScore: 0,
            isPaused: false, // 新增暂停状态
            // 初始化已达到的里程碑数组
            reachedMilestones: config.milestoneScores.map(() => false),
            achievedMilestones: [] // 新增已达成里程碑数组
        };

        // DOM元素
        let elements = {};

        // 在状态管理模块添加追踪器
        const stateTracker = {
            lastMatched: [],
            logState() {
                console.table(gameState.grid.map(row => 
                    row.map(cell => `${cell}:matched`)
                ));
            }
        };

        // 使用will-change属性提升动画性能
        function applyWillChange(element, property) {
            element.style.willChange = property;
        }

        // 检查网格数据更新后是否触发重绘
        function updateGrid() {
            requestAnimationFrame(() => { // 请求动画帧优化渲染
                gameState.grid.forEach((row, i) => {
                    row.forEach((cell, j) => {
                        const domCell = document.querySelector(`[data-row="${i}"][data-col="${j}"]`);
                        if (domCell) {
                            // 在开发模式添加状态标记
                            const debugState = cell === null ? 'empty' : 'normal';
                            domCell.dataset.debugState = debugState;
                            
                            // 假设 devMode 为全局开发模式标志
                            const devMode = false; // 修改为 false 关闭调试状态显示
                            if (devMode) {
                                let debugCorner = domCell.querySelector('.debug-corner');
                                if (!debugCorner) {
                                    debugCorner = document.createElement('div');
                                    debugCorner.className = 'debug-corner';
                                    domCell.appendChild(debugCorner);
                                }
                                debugCorner.textContent = debugState;
                            }

                            if (cell === null) {
                                domCell?.classList.add('disappear'); // 确保添加消失动画类
                                stateTracker.lastMatched.push({ row: i, col: j });
                            }
                        }
                    });
                });
                stateTracker.logState();
            });
        }

        // 初始化本地存储数据，添加容错机制
        function initLocalStorage() {
            try {
                // 获取今日日期
                const today = new Date().toDateString();
                const storedDate = localStorage.getItem('gameDate');
                
                // 如果日期不匹配或没有存储，重置游戏次数
                if (storedDate !== today) {
                    localStorage.setItem('gameDate', today);
                    localStorage.setItem('playCount', '0');
                }
                
                // 获取游戏次数
                const playCount = localStorage.getItem('playCount');
                if (playCount !== null) {
                    gameState.playCount = parseInt(playCount);
                    elements.playCount.textContent = `今日挑战: ${gameState.playCount}次`;
                }
                
                // 获取最高分
                const highScore = localStorage.getItem('highScore');
                if (highScore !== null) {
                    gameState.highScore = parseInt(highScore);
                    elements.highScore.textContent = `最高分: ${gameState.highScore}`;
                }

                // 清除本地存储错误数据
                if(localStorage.getItem('targetScore') === '130') {
                    localStorage.removeItem('targetScore');
                }
            } catch (error) {
                console.error('本地存储出错:', error);
            }
        }

        // 保存游戏次数，添加容错机制
        function savePlayCount() {
            try {
                gameState.playCount++;
                localStorage.setItem('playCount', gameState.playCount.toString());
                elements.playCount.textContent = `今日挑战: ${gameState.playCount}次`;
            } catch (error) {
                console.error('保存游戏次数出错:', error);
            }
        }

        // 保存最高分，添加容错机制
        function saveHighScore(score) {
            try {
                if (score > gameState.highScore) {
                    gameState.highScore = score;
                    localStorage.setItem('highScore', gameState.highScore.toString());
                    elements.highScore.textContent = `最高分: ${gameState.highScore}`;
                }
            } catch (error) {
                console.error('保存最高分出错:', error);
            }
        }

        // 初始化游戏网格
        function initializeGrid() {
            gameState.grid = [];
            elements.gameGrid.innerHTML = '';
            
            // 创建初始网格
            for (let row = 0; row < config.gridSize; row++) {
                gameState.grid[row] = [];
                for (let col = 0; col < config.gridSize; col++) {
                    // 确保不会在初始化时就有匹配的三个
                    let validItem = false;
                    let item;
                    while (!validItem) {
                        item = config.itemTypes[Math.floor(Math.random() * config.itemTypes.length)];
                        validItem = true;
                        
                        // 检查水平方向
                        if (col >= 2) {
                            if (gameState.grid[row][col-1] === item && gameState.grid[row][col-2] === item) {
                                validItem = false;
                            }
                        }
                        
                        // 检查垂直方向
                        if (row >= 2) {
                            if (gameState.grid[row-1][col] === item && gameState.grid[row-2][col] === item) {
                                validItem = false;
                            }
                        }
                    }
                    
                    gameState.grid[row][col] = item;
                    
                    // 创建网格项元素
                    const itemElement = document.createElement('div');
                    itemElement.className = 'fruit-item bg-white rounded-lg shadow-md flex items-center justify-center text-[clamp(2rem,5vw,2.4rem)] h-20 w-20 cursor-pointer mx-auto';
                    itemElement.dataset.row = row;
                    itemElement.dataset.col = col;
                    itemElement.textContent = item;
                    
                    // 添加点击事件
                    itemElement.addEventListener('click', () => handleItemClick(row, col));
                    
                    // 添加到DOM
                    elements.gameGrid.appendChild(itemElement);
                }
            }
        }

        // 处理网格项点击，优化无效交换回滚机制
        function handleItemClick(row, col) {
            if (!gameState.isPlaying || gameState.isPaused) return;
            
            const item = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
            if (!item) return;
            
            // 如果是第一次选择
            if (gameState.firstSelected === null) {
                gameState.firstSelected = { row, col, element: item };
                item.classList.add('ring-2', 'ring-primary', 'ring-offset-2');
                return;
            }
            
            // 如果是第二次选择
            const { row: firstRow, col: firstCol, element: firstElement } = gameState.firstSelected;
            
            // 检查是否是相邻格子
            const isAdjacent = (
                (Math.abs(row - firstRow) === 1 && col === firstCol) || 
                (Math.abs(col - firstCol) === 1 && row === firstRow)
            );
            
            if (isAdjacent) {
                // 交换两个格子
                swapItems(firstRow, firstCol, row, col);
                
                // 重置选择状态
                firstElement.classList.remove('ring-2', 'ring-primary', 'ring-offset-2');
                gameState.firstSelected = null;
                
                // 检查是否形成匹配，适当缩短定时器时间
                setTimeout(() => {
                    const matches = findMatches();
                    if (matches.length > 0) {
                        processMatches(matches);
                    } else {
                        // 如果没有匹配，交换回来
                        setTimeout(() => {
                            // 记录原始网格状态
                            const originalGrid = JSON.parse(JSON.stringify(gameState.grid));
                            // 交换数据
                            const temp = gameState.grid[row][col];
                            gameState.grid[row][col] = gameState.grid[firstRow][firstCol];
                            gameState.grid[firstRow][firstCol] = temp;
                            
                            // 检查交换后是否仍无匹配
                            const newMatches = findMatches();
                            if (newMatches.length === 0) {
                                // 恢复原始网格状态
                                gameState.grid = originalGrid;
                            }
                            
                            // 交换 DOM 显示
                            swapItems(row, col, firstRow, firstCol);
                            showMessage("没有匹配，再试一次！", 'warning');
                        }, 300); // 调整交换回来的时间
                    }
                }, 300); // 调整检查匹配的时间
            } else {
                // 如果不是相邻格子，取消第一次选择，选择当前格子
                firstElement.classList.remove('ring-2', 'ring-primary', 'ring-offset-2');
                gameState.firstSelected = { row, col, element: item };
                item.classList.add('ring-2', 'ring-primary', 'ring-offset-2');
            }
        }

        // 交换两个格子，使用will-change属性提升动画性能
        function swapItems(row1, col1, row2, col2) {
            // 交换数据
            const temp = gameState.grid[row1][col1];
            gameState.grid[row1][col1] = gameState.grid[row2][col2];
            gameState.grid[row2][col2] = temp;
            
            // 交换 DOM 显示
            const element1 = document.querySelector(`[data-row="${row1}"][data-col="${col1}"]`);
            const element2 = document.querySelector(`[data-row="${row2}"][data-col="${col2}"]`);
            
            if (element1 && element2) {
                // 使用will-change属性
                applyWillChange(element1, 'transform');
                applyWillChange(element2, 'transform');
                
                // 记录原始位置
                const rect1 = element1.getBoundingClientRect();
                const rect2 = element2.getBoundingClientRect();
                
                // 记录原始定位样式
                const originalPosition1 = element1.style.position;
                const originalPosition2 = element2.style.position;
                element1.style.position = 'relative'; // 修改为 relative 定位
                element2.style.position = 'relative'; // 修改为 relative 定位
                element1.style.zIndex = '10';
                element2.style.zIndex = '10';
                
                // 立即更新位置
                element1.style.transform = `translate(${rect2.left - rect1.left}px, ${rect2.top - rect1.top}px)`;
                element2.style.transform = `translate(${rect1.left - rect2.left}px, ${rect1.top - rect2.top}px)`;
                
                // 添加过渡效果
                element1.style.transition = 'transform 0.3s ease';
                element2.style.transition = 'transform 0.3s ease';
                
                // 延迟重置样式
                setTimeout(() => {
                    element1.style.position = originalPosition1;
                    element2.style.position = originalPosition2;
                    element1.style.zIndex = '';
                    element2.style.zIndex = '';
                    element1.style.transform = '';
                    element2.style.transform = '';
                    element1.style.transition = '';
                    element2.style.transition = '';
                    element1.style.willChange = '';
                    element2.style.willChange = '';
                    
                    // 更新内容
                    const tempContent = element1.textContent;
                    element1.textContent = element2.textContent;
                    element2.textContent = tempContent;
                }, 300);
            }
        }

        // 查找所有匹配
        function findMatches() {
            const matches = [];
            
            // 检查水平匹配
            for (let row = 0; row < config.gridSize; row++) {
                for (let col = 0; col < config.gridSize - 2; col++) {
                    const current = gameState.grid[row][col];
                    if (current && 
                        current === gameState.grid[row][col+1] && 
                        current === gameState.grid[row][col+2]) {
                        
                        // 找到水平匹配，检查是否有更多连续的
                        let matchLength = 3;
                        while (col + matchLength < config.gridSize && 
                              current === gameState.grid[row][col + matchLength]) {
                            matchLength++;
                        }
                        
                        // 添加匹配信息
                        matches.push({
                            type: 'horizontal',
                            row,
                            col,
                            length: matchLength,
                            item: current
                        });
                        
                        // 跳过已经匹配的列
                        col += matchLength - 1;
                    }
                }
            }
            
            // 检查垂直匹配
            for (let col = 0; col < config.gridSize; col++) {
                for (let row = 0; row < config.gridSize - 2; row++) {
                    const current = gameState.grid[row][col];
                    if (current && 
                        current === gameState.grid[row+1][col] && 
                        current === gameState.grid[row+2][col]) {
                        
                        // 找到垂直匹配，检查是否有更多连续的
                        let matchLength = 3;
                        while (row + matchLength < config.gridSize && 
                              current === gameState.grid[row + matchLength][col]) {
                            matchLength++;
                        }
                        
                        // 添加匹配信息
                        matches.push({
                            type: 'vertical',
                            row,
                            col,
                            length: matchLength,
                            item: current
                        });
                        
                        // 跳过已经匹配的行
                        row += matchLength - 1;
                    }
                }
            }
            
            return matches;
        }

        // 处理匹配
        function processMatches(matches) {
            if (matches.length === 0) return;
            
            let scoreIncrement = 0;
            
            // 高亮显示匹配项
            const matchedPositions = new Set();
            matches.forEach(match => {
                // 计算得分 (3个基础分10，每多一个加5分)
                const matchScore = 10 + (match.length - 3) * 5;
                scoreIncrement += matchScore;
                
                // 特殊奖励
                if (match.length >= 4) {
                    const specialBonus = match.length === 4 ? 10 : 25;
                    scoreIncrement += specialBonus;
                    
                    // 显示特殊奖励信息
                    setTimeout(() => {
                        showMessage(
                            match.length === 4 ? "四连！获得炸弹奖励！" : "五连！获得彩虹水果奖励！", 
                            'success'
                        );
                    }, 200);

                    if (match.length === 4) {
                        // 四连炸弹处理
                        if (match.type === 'horizontal') {
                            // 消除一行
                            for (let col = 0; col < config.gridSize; col++) {
                                const row = match.row;
                                const element = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                                if (element) {
                                    element.classList.add('bomb-explode');
                                }
                            }
                            setTimeout(() => {
                                for (let col = 0; col < config.gridSize; col++) {
                                    const row = match.row;
                                    gameState.grid[row][col] = null;
                                    const element = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                                    if (element) {
                                        element.textContent = '';
                                        element.classList.remove('bomb-explode', 'scale-110', 'opacity-50', 'bg-primary/20');
                                        element.classList.add('bg-gray-100');
                                        matchedPositions.add(`${row},${col}`);
                                    }
                                }
                                // 下落填充
                                dropItems();
                            }, 800);
                        } else {
                            // 消除一列
                            for (let row = 0; row < config.gridSize; row++) {
                                const col = match.col;
                                const element = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                                if (element) {
                                    element.classList.add('bomb-explode');
                                }
                            }
                            setTimeout(() => {
                                for (let row = 0; row < config.gridSize; row++) {
                                    const col = match.col;
                                    gameState.grid[row][col] = null;
                                    const element = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                                    if (element) {
                                        element.textContent = '';
                                        element.classList.remove('bomb-explode', 'scale-110', 'opacity-50', 'bg-primary/20');
                                        element.classList.add('bg-gray-100');
                                        matchedPositions.add(`${row},${col}`);
                                    }
                                }
                                // 下落填充
                                dropItems();
                            }, 800);
                        }
                    } else if (match.length === 5) {
                        // 五连消除处理
                        // 计算五连的中心位置
                        const centerRow = match.type === 'horizontal' ? match.row : match.row + Math.floor(match.length / 2);
                        const centerCol = match.type === 'horizontal' ? match.col + Math.floor(match.length / 2) : match.col;

                        // 消除中心列和行
                        // 消除行
                        for (let col = 0; col < config.gridSize; col++) {
                            const element = document.querySelector(`[data-row="${centerRow}"][data-col="${col}"]`);
                            if (element) {
                                element.classList.add('bomb-explode');
                            }
                        }
                        // 消除列
                        for (let row = 0; row < config.gridSize; row++) {
                            const element = document.querySelector(`[data-row="${row}"][data-col="${centerCol}"]`);
                            if (element) {
                                element.classList.add('bomb-explode');
                            }
                        }

                        setTimeout(() => {
                            // 消除行
                            for (let col = 0; col < config.gridSize; col++) {
                                gameState.grid[centerRow][col] = null;
                                const element = document.querySelector(`[data-row="${centerRow}"][data-col="${col}"]`);
                                if (element) {
                                    element.textContent = '';
                                    element.classList.remove('bomb-explode', 'scale-110', 'opacity-50', 'bg-primary/20');
                                    element.classList.add('bg-gray-100');
                                    matchedPositions.add(`${centerRow},${col}`);
                                }
                            }
                            // 消除列
                            for (let row = 0; row < config.gridSize; row++) {
                                gameState.grid[row][centerCol] = null;
                                const element = document.querySelector(`[data-row="${row}"][data-col="${centerCol}"]`);
                                if (element) {
                                    element.textContent = '';
                                    element.classList.remove('bomb-explode', 'scale-110', 'opacity-50', 'bg-primary/20');
                                    element.classList.add('bg-gray-100');
                                    matchedPositions.add(`${row},${centerCol}`);
                                }
                            }
                            // 下落填充
                            dropItems();
                        }, 800);
                    }
                }
                
                // 标记匹配位置
                for (let i = 0; i < match.length; i++) {
                    const row = match.type === 'horizontal' ? match.row : match.row + i;
                    const col = match.type === 'horizontal' ? match.col + i : match.col;
                    if (match.length !== 4 || (row === match.row && col === match.col)) {
                        matchedPositions.add(`${row},${col}`);
                        
                        // 添加匹配动画
                        const element = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                        if (element) {
                            element.classList.add('scale-110', 'opacity-50', 'bg-primary/20');
                            
                            // 添加得分显示
                            const scorePopup = document.createElement('div');
                            scorePopup.className = 'score-popup absolute text-white font-bold text-lg bg-primary/80 rounded-full px-3 py-1';
                            scorePopup.textContent = `+${matchScore}`;
                            scorePopup.style.left = `${element.offsetLeft + element.offsetWidth/2}px`;
                            scorePopup.style.top = `${element.offsetTop - 30}px`;
                            document.body.appendChild(scorePopup);
                            
                            // 移除得分显示
                            setTimeout(() => {
                                scorePopup.remove();
                            }, 800);
                        }
                    }
                }
            });
            
            // 更新分数
            updateScore(scoreIncrement);
            
            // 播放匹配音效
            playSound('match');
            
            // 延迟后移除匹配项并填充新项
            setTimeout(() => {
                // 移除匹配项
                matchedPositions.forEach(pos => {
                    const [row, col] = pos.split(',').map(Number);
                    gameState.grid[row][col] = null;
                    
                    const element = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                    if (element) {
                        element.textContent = '';
                        element.classList.remove('scale-110', 'opacity-50', 'bg-primary/20');
                        element.classList.add('bg-gray-100');
                    }
                });
                
                // 下落填充
                setTimeout(() => {
                    dropItems();
                    
                    // 检查是否有新的匹配
                    setTimeout(() => {
                        const newMatches = findMatches();
                        if (newMatches.length > 0) {
                            processMatches(newMatches);
                        } else {
                            // 检查游戏是否结束
                            if (!canMakeMove()) {
                                endGame(true);
                            }
                        }
                    }, 600);
                }, 300);
            }, 500);
            updateGrid(); // 调用更新网格函数
        }

        // 下落填充空白位置，使用will-change属性提升动画性能
        function dropItems() {
            // 对每一列处理
            for (let col = 0; col < config.gridSize; col++) {
                // 记录每列的下落距离
                const dropDistances = new Array(config.gridSize).fill(0);
                let dropDistance = 0;
                
                // 从底部向上处理
                for (let row = config.gridSize - 1; row >= 0; row--) {
                    if (gameState.grid[row][col] === null) {
                        dropDistance++;
                    } else if (dropDistance > 0) {
                        // 记录当前元素需要下落的距离
                        dropDistances[row] = dropDistance;
                        
                        // 下移元素
                        gameState.grid[row + dropDistance][col] = gameState.grid[row][col];
                        gameState.grid[row][col] = null;
                        
                        // 更新DOM
                        const element = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                        const targetElement = document.querySelector(`[data-row="${row + dropDistance}"][data-col="${col}"]`);
                        
                        if (element && targetElement) {
                            // 使用will-change属性
                            applyWillChange(targetElement, 'transform');
                            
                            // 添加平滑下落动画
                            targetElement.textContent = element.textContent;
                            targetElement.classList.remove('bg-gray-100');
                            targetElement.classList.add('smooth-drop');
                            targetElement.style.transform = `translateY(-${dropDistance * (targetElement.offsetHeight + 8)}px)`;
                            
                            // 重置动画
                            setTimeout(() => {
                                targetElement.style.transform = '';
                                targetElement.classList.remove('smooth-drop');
                                targetElement.style.willChange = '';
                            }, 300);
                            
                            element.textContent = '';
                            element.classList.add('bg-gray-100');
                        }
                    }
                }
            }
            
            // 顶部填充新元素
            setTimeout(fillTop, 350);
        }

        // 顶部填充新元素，使用will-change属性提升动画性能
        function fillTop() {
            let newItemsAdded = false;
            
            // 对每一列处理
            for (let col = 0; col < config.gridSize; col++) {
                // 从顶部向下查找空位置
                for (let row = 0; row < config.gridSize; row++) {
                    if (gameState.grid[row][col] === null) {
                        // 生成新元素
                        const newItem = config.itemTypes[Math.floor(Math.random() * config.itemTypes.length)];
                        gameState.grid[row][col] = newItem;
                        newItemsAdded = true;
                        
                        // 更新DOM
                        const element = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                        if (element) {
                            // 使用will-change属性
                            applyWillChange(element, 'transform');
                            
                            element.textContent = newItem;
                            element.classList.remove('bg-gray-100');
                            
                            // 添加新元素动画
                            element.classList.add('scale-125');
                            setTimeout(() => {
                                element.classList.remove('scale-125');
                                element.style.willChange = '';
                            }, 300);
                        }
                    }
                }
            }
            
            // 如果有新元素添加，播放音效
            if (newItemsAdded) {
                playSound('drop');
            }
        }

        // 检查是否还有可移动的步骤
        function canMakeMove() {
            // 简单检查：尝试交换每对相邻元素，看是否能形成匹配
            for (let row = 0; row < config.gridSize; row++) {
                for (let col = 0; col < config.gridSize; col++) {
                    // 尝试向右交换
                    if (col < config.gridSize - 1) {
                        // 交换
                        [gameState.grid[row][col], gameState.grid[row][col+1]] = 
                        [gameState.grid[row][col+1], gameState.grid[row][col]];
                        
                        // 检查匹配
                        const matches = findMatches();
                        
                        // 交换回来
                        [gameState.grid[row][col], gameState.grid[row][col+1]] = 
                        [gameState.grid[row][col+1], gameState.grid[row][col]];
                        
                        if (matches.length > 0) return true;
                    }
                    
                    // 尝试向下交换
                    if (row < config.gridSize - 1) {
                        // 交换
                        [gameState.grid[row][col], gameState.grid[row+1][col]] = 
                        [gameState.grid[row+1][col], gameState.grid[row][col]];
                        
                        // 检查匹配
                        const matches = findMatches();
                        
                        // 交换回来
                        [gameState.grid[row][col], gameState.grid[row+1][col]] = 
                        [gameState.grid[row+1][col], gameState.grid[row][col]];
                        
                        if (matches.length > 0) return true;
                    }
                }
            }
            
            return false;
        }

        // 使用提示
        function useHint() {
            if (!gameState.isPlaying || gameState.hintCount <= 0 || gameState.isPaused) return;
            
            // 减少提示次数
            gameState.hintCount--;
            elements.gameHintCount.textContent = `${gameState.hintCount} 次提示`;
            
            // 寻找可移动的位置
            for (let row = 0; row < config.gridSize; row++) {
                for (let col = 0; col < config.gridSize; col++) {
                    // 尝试向右交换
                    if (col < config.gridSize - 1) {
                        // 交换
                        [gameState.grid[row][col], gameState.grid[row][col+1]] = 
                        [gameState.grid[row][col+1], gameState.grid[row][col]];
                        
                        // 检查匹配
                        const matches = findMatches();
                        
                        // 交换回来
                        [gameState.grid[row][col], gameState.grid[row][col+1]] = 
                        [gameState.grid[row][col+1], gameState.grid[row][col]];
                        
                        if (matches.length > 0) {
                            // 高亮提示位置
                            const element1 = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                            const element2 = document.querySelector(`[data-row="${row}"][data-col="${col+1}"]`);
                            
                            if (element1 && element2) {
                                element1.classList.add('ring-2', 'ring-yellow-500', 'ring-offset-2', 'animate-pulse');
                                element2.classList.add('ring-2', 'ring-yellow-500', 'ring-offset-2', 'animate-pulse');
                                
                                // 5秒后取消高亮
                                setTimeout(() => {
                                    element1.classList.remove('ring-2', 'ring-yellow-500', 'ring-offset-2', 'animate-pulse');
                                    element2.classList.remove('ring-2', 'ring-yellow-500', 'ring-offset-2', 'animate-pulse');
                                }, 5000);
                            }
                            
                            // 提示使用后冷却
                            gameState.hintAvailable = false;
                            elements.gameHintBtn.disabled = true;
                            elements.gameHintBtn.classList.add('opacity-50', 'cursor-not-allowed');
                            
                            // 开始冷却倒计时
                            let cooldown = config.hintCooldown;
                            const originalText = elements.gameHintBtn.innerHTML;
                            elements.gameHintBtn.innerHTML = `<i class="fa-regular fa-lightbulb"></i> ${cooldown}s`;
                            
                            const hintCooldownInterval = setInterval(() => {
                                cooldown--;
                                if (cooldown <= 0) {
                                    clearInterval(hintCooldownInterval);
                                    elements.gameHintBtn.innerHTML = `<i class="fa-regular fa-lightbulb"></i> ${gameState.hintCount} 次提示`;
                                    elements.gameHintBtn.disabled = false;
                                    elements.gameHintBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                                    gameState.hintAvailable = true;
                                } else {
                                    elements.gameHintBtn.innerHTML = `<i class="fa-regular fa-lightbulb"></i> ${cooldown}s`;
                                }
                            }, 1000);
                            
                            return;
                        }
                    }
                    
                    // 尝试向下交换
                    if (row < config.gridSize - 1) {
                        // 交换
                        [gameState.grid[row][col], gameState.grid[row+1][col]] = 
                        [gameState.grid[row+1][col], gameState.grid[row][col]];
                        
                        // 检查匹配
                        const matches = findMatches();
                        
                        // 交换回来
                        [gameState.grid[row][col], gameState.grid[row+1][col]] = 
                        [gameState.grid[row+1][col], gameState.grid[row][col]];
                        
                        if (matches.length > 0) {
                            // 高亮提示位置
                            const element1 = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
                            const element2 = document.querySelector(`[data-row="${row+1}"][data-col="${col}"]`);
                            
                            if (element1 && element2) {
                                element1.classList.add('ring-2', 'ring-yellow-500', 'ring-offset-2', 'animate-pulse');
                                element2.classList.add('ring-2', 'ring-yellow-500', 'ring-offset-2', 'animate-pulse');
                                
                                // 5秒后取消高亮
                                setTimeout(() => {
                                    element1.classList.remove('ring-2', 'ring-yellow-500', 'ring-offset-2', 'animate-pulse');
                                    element2.classList.remove('ring-2', 'ring-yellow-500', 'ring-offset-2', 'animate-pulse');
                                }, 5000);
                            }
                            
                            // 提示使用后冷却
                            gameState.hintAvailable = false;
                            elements.gameHintBtn.disabled = true;
                            elements.gameHintBtn.classList.add('opacity-50', 'cursor-not-allowed');
                            
                            // 开始冷却倒计时
                            let cooldown = config.hintCooldown;
                            const originalText = elements.gameHintBtn.innerHTML;
                            elements.gameHintBtn.innerHTML = `<i class="fa-regular fa-lightbulb"></i> ${cooldown}s`;
                            
                            const hintCooldownInterval = setInterval(() => {
                                cooldown--;
                                if (cooldown <= 0) {
                                    clearInterval(hintCooldownInterval);
                                    elements.gameHintBtn.innerHTML = `<i class="fa-regular fa-lightbulb"></i> ${gameState.hintCount} 次提示`;
                                    elements.gameHintBtn.disabled = false;
                                    elements.gameHintBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                                    gameState.hintAvailable = true;
                                } else {
                                    elements.gameHintBtn.innerHTML = `<i class="fa-regular fa-lightbulb"></i> ${cooldown}s`;
                                }
                            }, 1000);
                            
                            return;
                        }
                    }
                }
            }
            showMessage("暂时没有可提示的步骤！", 'warning');
        }

        // 更新分数
        function updateScore(increment) {
            gameState.score += increment;
            
            // 更新显示
            elements.gameScore.textContent = gameState.score;

            // ====== 新增弹窗类型检测 ======
            checkScoreTriggers(gameState.score);

            // 检查是否达到目标分数
            if (gameState.score >= config.targetScore) {
                endGame(true);
            }
        }

        // ====== 新增弹窗类型检测 ======
        function checkScoreTriggers(currentScore) {
            // 目标达成检测（仅在达到1000分时触发）
            if (currentScore >= config.targetScore) {
                showTargetCompleteModal();  // 使用独立弹窗函数
                return;
            }
            
            // 里程碑检测（只处理配置中的分数）
            checkMilestone(currentScore);
        }

        // ====== 独立目标完成弹窗 ======
        function showTargetCompleteModal() {
            const modal = document.getElementById('target-modal');
            modal.querySelector('.score').textContent = gameState.score;
            modal.classList.remove('hidden');
            pauseGame(); // 暂停游戏
        }

        // ====== 增强型里程碑检测 ======
        function checkMilestone(currentScore) {
            config.milestoneScores.forEach(score => {
                if (currentScore >= score && 
                    !gameState.achievedMilestones.includes(score)) {
                    showMilestoneModal(score);
                    gameState.achievedMilestones.push(score);
                }
            });
        }

        // ====== 增加弹窗互斥锁 ======
        let isModalShowing = false;
        function showMilestoneModal(score) {
            if (isModalShowing) return;
            isModalShowing = true;
            // 创建新的里程碑对话框
            const dialog = document.createElement('div');
            dialog.className = 'fixed inset-0 bg-dark/60 flex items-center justify-center z-50';
            dialog.innerHTML = `
                <div class="bg-white rounded-2xl p-8 max-w-md w-full text-center">
                    <h2 class="text-2xl font-comic font-bold text-primary mb-4">恭喜你! 太棒了！你获得了 ${score} 分，成功完成里程碑！</h2>
                    <p class="text-gray-600 mb-6">是否继续游戏？</p>
                    <div class="flex gap-4 justify-center">
                        <button id="continueGameBtn" class="bg-gradient-btn hover:opacity-95 text-white px-8 py-3 rounded-lg shadow-lg btn-hover text-lg font-comic">
                            是
                        </button>
                        <button id="restartGameBtn" class="bg-gradient-btn hover:opacity-95 text-white px-8 py-3 rounded-lg shadow-lg btn-hover text-lg font-comic">
                            否
                        </button>
                    </div>
                </div>
            `;
            document.body.appendChild(dialog);

            const continueGameBtn = dialog.querySelector('#continueGameBtn');
            const restartGameBtn = dialog.querySelector('#restartGameBtn');

            continueGameBtn.addEventListener('click', () => {
                document.body.removeChild(dialog);
                isModalShowing = false;
            });

            restartGameBtn.addEventListener('click', () => {
                document.body.removeChild(dialog);
                isModalShowing = false;
                endGame(false);
                resetGame();
            });
        }

        // 显示消息
        function showMessage(message, type = 'info') {
            // 创建消息元素
            const messageElement = document.createElement('div');
            messageElement.className = `fixed top-20 left-1/2 transform -translate-x-1/2 px-6 py-3 rounded-lg shadow-lg z-50 transition-all duration-500 opacity-0`;
            
            // 根据类型设置样式
            if (type === 'success') {
                messageElement.classList.add('bg-success', 'text-white');
            } else if (type === 'warning') {
                messageElement.classList.add('bg-warning', 'text-dark');
            } else {
                messageElement.classList.add('bg-info', 'text-white');
            }
            
            messageElement.textContent = message;
            document.body.appendChild(messageElement);
            
            // 显示消息
            setTimeout(() => {
                messageElement.classList.remove('opacity-0');
                messageElement.classList.add('opacity-100');
            }, 100);
            
            // 自动消失
            setTimeout(() => {
                messageElement.classList.remove('opacity-100');
                messageElement.classList.add('opacity-0');
                setTimeout(() => {
                    messageElement.remove();
                }, 500);
            }, 2000);
        }

        // 播放音效
        function playSound(type) {
            if (!gameState.soundEnabled || gameState.isPaused) return;
            
            // 实际项目中应该使用真正的音频文件
            // 这里仅作示例
            console.log(`Playing sound: ${type}`);
        }

        // 开始游戏
        function startGame() {
            // 隐藏开始按钮和显示游戏区域
            elements.gameArea.classList.remove('hidden');
            
            // 初始化游戏状态
            gameState.score = 0;
            gameState.timeRemaining = config.timeLimit;
            gameState.isPlaying = false;
            gameState.firstSelected = null;
            gameState.hintCount = config.hintCount;
            gameState.hintAvailable = true;
            gameState.isPaused = false;
            // 重置已达到的里程碑数组
            gameState.reachedMilestones = config.milestoneScores.map(() => false);
            gameState.achievedMilestones = []; // 重置已达成里程碑数组

            // 更新UI
            elements.gameScore.textContent = gameState.score;
            // 修改初始计时器显示为 3:30
            elements.gameTimer.textContent = '3:30'; 
            elements.gameHintCount.textContent = `${gameState.hintCount} 次提示`;
            elements.gameHintBtn.disabled = false;
            elements.gameHintBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            elements.timeProgress.style.width = '100%';
            elements.timeProgress.classList.remove('bg-danger', 'animate-pulse');
            elements.pauseBtn.innerHTML = '<i class="fa-solid fa-pause text-2xl"></i> <span>暂停游戏</span>';
            
            // 初始化网格
            initializeGrid();

            // 直接开始游戏倒计时
            startGameCountdown();
        }

        // 真正开始游戏倒计时
        function startGameCountdown() {
            // 保存游戏次数
            savePlayCount();
            
            // 设置游戏状态
            gameState.isPlaying = true;
            
            // 开始计时器
            gameState.timerInterval = setInterval(updateTimer, 1000);
            
            // 启用提示按钮
            setTimeout(() => {
                gameState.hintAvailable = true;
                elements.gameHintBtn.disabled = false;
                elements.gameHintBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            }, 2000);
        }

        // 暂停游戏
        function pauseGame() {
            gameState.isPaused = true;
            clearInterval(gameState.timerInterval);
            elements.pauseBtn.innerHTML = '<i class="fa-solid fa-play text-2xl"></i> <span>继续游戏</span>';
        }

        // 继续游戏
        function resumeGame() {
            gameState.isPaused = false;
            gameState.timerInterval = setInterval(updateTimer, 1000);
            elements.pauseBtn.innerHTML = '<i class="fa-solid fa-pause text-2xl"></i> <span>暂停游戏</span>';
        }

        // 切换暂停状态
        function togglePause() {
            if (gameState.isPaused) {
                resumeGame();
            } else {
                pauseGame();
            }
        }

        // 初始化修复
        function initGame() {
            // 强制重置目标状态
            gameState = {
                ...gameState,
                score: 0,
                achievedMilestones: gameState.achievedMilestones.filter(s => s >= 150)
            };
            
            // 清除本地存储错误数据
            if(localStorage.getItem('targetScore') === '130') {
                localStorage.removeItem('targetScore');
            }
            initLocalStorage();
        }

        // 重置游戏
        function resetGame() {
            // 停止计时器
            clearInterval(gameState.timerInterval);
            
            // 隐藏游戏结束遮罩
            elements.gameOverOverlay.classList.add('hidden');
            elements.gameResultModal.classList.remove('scale-100', 'opacity-100');
            elements.gameResultModal.classList.add('scale-95', 'opacity-0');

            // 重新开始游戏
            startGame();
        }

        // 结束游戏
        function endGame(isSuccess) {
            // 确保计时器停止
            clearInterval(gameState.timerInterval);
            gameState.isPlaying = false;
            gameState.isPaused = false;
            
            // 保存最高分
            saveHighScore(gameState.score);
            
            // 显示游戏结束遮罩
            elements.gameOverOverlay.classList.remove('hidden');
            
            // 延迟显示结果，让动画更流畅
            setTimeout(() => {
                elements.gameResultModal.classList.remove('scale-95', 'opacity-0');
                elements.gameResultModal.classList.add('scale-100', 'opacity-100');
                
                // 设置结果文本
                if (isSuccess) {
                    elements.resultTitle.textContent = "恭喜你!";
                    elements.resultTitle.classList.add('text-success');
                    elements.resultMessage.innerHTML = `太棒了！你获得了 <span class="font-bold text-dark">${gameState.score}</span> 分，成功完成目标！`;
                } else {
                    elements.resultTitle.textContent = "时间到!";
                    elements.resultTitle.classList.add('text-danger');
                    elements.resultMessage.innerHTML = `你获得了 <span class="font-bold text-dark">${gameState.score}</span> 分，再接再厉！`;
                }
                
                // 设置星星评级
                elements.finalScore.textContent = gameState.score;
                const starsContainer = elements.resultStars;
                starsContainer.innerHTML = '';
                
                // 计算星星数量 (300分1星，450分2星，600分3星)
                let stars = 0;
                if (gameState.score >= 600) {
                    stars = 3;
                } else if (gameState.score >= 450) {
                    stars = 2;
                } else if (gameState.score >= 300) {
                    stars = 1;
                }
                
                // 添加星星
                for (let i = 0; i < 3; i++) {
                    const star = document.createElement('i');
                    star.className = `fa-${i < stars ? 'solid' : 'regular'} fa-star text-${i < stars ? 'yellow-400' : 'gray-300'} text-2xl transition-all duration-500`;
                    starsContainer.appendChild(star);
                }

                // 显示再玩一次和重置游戏按钮
                elements.playAgainBtn.classList.remove('hidden');
                elements.resetGameBtn.classList.remove('hidden');
            }, 300);
        }

        // 更新计时器，倒计时最后30秒红色警示
        function updateTimer() {
            if (gameState.isPaused) return;
            gameState.timeRemaining--;
            if (gameState.timeRemaining < 0) {
                endGame(false);
                return;
            }
            const minutes = Math.floor(gameState.timeRemaining / 60);
            const seconds = gameState.timeRemaining % 60;
            elements.gameTimer.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;
            elements.timeProgress.style.width = `${(gameState.timeRemaining / config.timeLimit) * 100}%`;
            if (gameState.timeRemaining < 30) {
                elements.timeProgress.classList.add('bg-danger', 'animate-pulse');
            } else {
                elements.timeProgress.classList.remove('bg-danger', 'animate-pulse');
            }
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', () => {
            // DOM元素
            elements = {
                startBtn: document.getElementById('startBtn'),
                gameArea: document.getElementById('gameArea'),
                gameGrid: document.getElementById('gameGrid'),
                gameHintBtn: document.getElementById('gameHintBtn'),
                gameHintCount: document.getElementById('gameHintCount'),
                gameScore: document.getElementById('gameScore'),
                gameTimer: document.getElementById('gameTimer'),
                gameTarget: document.getElementById('gameTarget'),
                gameStartOverlay: document.getElementById('gameStartOverlay'),
                overlayStartBtn: document.getElementById('overlayStartBtn'),
                gameOverOverlay: document.getElementById('gameOverOverlay'),
                gameResultModal: document.getElementById('gameResultModal'),
                resultTitle: document.getElementById('resultTitle'),
                resultMessage: document.getElementById('resultMessage'),
                finalScore: document.getElementById('finalScore'),
                resultStars: document.getElementById('resultStars'),
                playAgainBtn: document.getElementById('playAgainBtn'),
                timeProgress: document.getElementById('timeProgress'),
                ruleToggle: document.getElementById('ruleToggle'),
                rulePanel: document.getElementById('rulePanel'),
                shareResultBtn: document.getElementById('shareResultBtn'),
                shareModal: document.getElementById('shareModal'),
                shareModalContent: document.getElementById('shareModalContent'),
                closeShareBtn: document.getElementById('closeShareBtn'),
                hintInfoBtn: document.getElementById('hintInfoBtn'),
                hintInfoModal: document.getElementById('hintInfoModal'),
                hintInfoContent: document.getElementById('hintInfoContent'),
                closeHintInfoBtn: document.getElementById('closeHintInfoBtn'),
                playCount: document.getElementById('playCount'),
                highScore: document.getElementById('highScore'),
                resetGameBtn: document.getElementById('resetGameBtn'),
                pauseBtn: document.getElementById('pauseBtn')
            };

            // 初始化本地存储
            initGame();

            // 新增：给开始游戏按钮添加点击事件监听
            elements.startBtn.addEventListener('click', startGame);

            // 新增：给再玩一次按钮添加点击事件监听
            elements.playAgainBtn.addEventListener('click', resetGame);

            // 新增：给重置游戏按钮添加点击事件监听
            elements.resetGameBtn.addEventListener('click', resetGame);

            // 新增：给使用提示按钮添加点击事件监听
            elements.gameHintBtn.addEventListener('click', useHint);

            // 新增：给知道了按钮添加点击事件监听（提示信息模态框）
            elements.closeHintInfoBtn.addEventListener('click', () => {
                elements.hintInfoContent.classList.remove('scale-100', 'opacity-100');
                elements.hintInfoContent.classList.add('scale-95', 'opacity-0');
                setTimeout(() => {
                    elements.hintInfoModal.classList.add('hidden');
                }, 300);
            });

            // 新增：给规则切换按钮添加点击事件监听
            elements.ruleToggle.addEventListener('click', () => {
                elements.rulePanel.classList.toggle('hidden');
                const chevron = elements.ruleToggle.querySelector('i');
                chevron.classList.toggle('fa-chevron-down');
                chevron.classList.toggle('fa-chevron-up');
            });

            // 新增：给暂停按钮添加点击事件监听
            elements.pauseBtn.addEventListener('click', togglePause);
        });
    </script>
</body>
</html>
   